﻿using System;
using System.Text;
using System.Windows.Data;
using System.Windows.Markup;
namespace TciNewsReader_2014_04.Converters
{
    public class DateToTimeSpanConverter:MarkupExtension, IValueConverter
    {
        public DateToTimeSpanConverter(){}
        private static readonly char[] Trimmers;
        static DateToTimeSpanConverter()
        {
            Trimmers = new[] {',', ' '};
        }
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try
            {
                DateTime dt = (DateTime) value;
                TimeSpan ts = DateTime.Now - dt;
                StringBuilder sb = new StringBuilder();
                if (ts.Days > 0)
                {
                    sb.AppendFormat("{0} {1}, ", ts.Days, QuantityOf(ts.Days, "day"));
                }
                if (ts.Hours > 0)
                {
                    sb.AppendFormat("{0} {1}, ", ts.Hours, QuantityOf(ts.Hours, "hour"));
                }
                if (ts.Minutes > 0)
                {
                    sb.AppendFormat("{0} {1}, ", ts.Minutes, QuantityOf(ts.Minutes, "minute"));
                }
                if (sb.ToString().Length == 0)
                {
                    sb.Append("Less than a minute");
                }
                string result = sb.ToString().Trim(Trimmers);
                result += " ago.";
                return result;
            }
            catch (Exception)
            {
                return String.Empty;
            }
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }
        private string QuantityOf(int quantity, string singular)
        {
            if (quantity == 1) return singular;
            return singular + "s";
        }
    }
}
